package com.colourclash.fruitopia.utils
{
	
	import com.colourclash.fruitopia.events.InitialisedEvent;
	import com.colourclash.fruitopia.events.PropertyChangeEvent;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.utils.*;
	
	/**
	 * ...
	 * @author Patrick
	 */
	public class BaseView extends Sprite
	{
				
		private var _descriptor:XML;
		
		protected var controller:BaseController;
		
		public function BaseView(controller:BaseController)
		{
			this.controller = controller;
			
			_descriptor = describeType(this);
			
			viewStage.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, propertyChangeHander, false, 0, true);
			
			viewStage.dispatchEvent(new InitialisedEvent(InitialisedEvent.VIEW_INITIALISED, controller.id, true));
		}

		public function get viewStage():Stage
		{
			return Global.getInstance().stage;
		}
		
		private function propertyChangeHander(e:PropertyChangeEvent):void
		{
			if (e.sender['id'] == controller.id)
			{
				//trace(e.sender['id'] + " -> " + id);
				var hasSetter:Boolean = _descriptor.accessor.(@name == e.propertyName).@access.toString().indexOf("write") > -1;
				
				if (hasSetter)
					this[e.propertyName] = e.sender[e.propertyName];
				
				modelPropertyChanged(e.propertyName, e.sender[e.propertyName], e.args);
			}
		}
		
		protected function modelPropertyChanged(propertyName:String, propertyValue:Object, args:Array):void
		{
			//override if need be				
		}

	
	}
}